package com.jy.oms.framework.thread;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 可关闭线程
 *
 * @author liuquan
 */
@Component
public class CloseableThreadManager implements ApplicationListener<ContextClosedEvent> {
    private static Logger logger = LoggerFactory.getLogger(CloseableThreadManager.class);

    private List<CloseableThread> closeableThreads = new ArrayList<>();

    public void regist(CloseableThread thread) {
        closeableThreads.add(thread);
    }

    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        gracefulStop();
    }

    public void gracefulStop(){
        logger.info("开始关闭应用，开始停止无限循环线程, CloseableThread size:{}", closeableThreads.size());
        closeableThreads.forEach(thread -> thread.toStop());
    }
}
